extends Area2D

export (int) var speed = 560
export (int) var damage = 12
export (float) var lifetime = 0.7
export (float) var steer_force = 0	#导航力度,0的话就是没有导航。

var velocity = Vector2()
var acceleration = Vector2()
var target :Node = null	#攻击目标
var alive = true

#初始化子弹（位置，方向，目标）
func start(_position, _direction, _target = null):
	position = _position
	rotation = _direction.angle()
	$Lifetime.wait_time = lifetime
	$Lifetime.start()
	velocity = _direction * speed
	target = _target

func explode():
	alive =false
	velocity = Vector2.ZERO
	$Sprite.hide()
	$Explosion.show()
	$Explosion.play("fire")
	
func seek():
	#指向目标的速度矢量
	var desired = (target.global_position - global_position).normalized() * speed
	#修正速度矢量
	var steer = (desired - velocity).normalized() * steer_force

	return steer

func _process(delta):
	if not alive: return
	if target and is_instance_valid(target): #修正速度
		acceleration += seek()
		velocity += acceleration * delta
		velocity = velocity.clamped(speed)
		rotation = velocity.angle()
		
	position += velocity * delta


func _on_Lifetime_timeout():
	explode()


func _on_Bullet_body_entered(body):
	explode()
	if body.has_method("take_damage"):
		body.take_damage(damage)


func _on_Explosion_animation_finished():
	queue_free()
